<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 搜索 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字: " prop="keyWordsStr">
              <el-input v-model="form.keyWordsStr" @keyup.enter.native="searchRandoms" placeholder="根据编号搜索" class="ipt"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="btn">
              <el-button type="reset" size="small" @click="form.keyWordsStr=null">清除</el-button>
              <el-button type="primary" size="small" @click="searchRandoms" :disabled="isLoading">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 共几条数据 -->
      <el-alert type="info" :closable="false" show-icon :title="alertText"></el-alert>
      <!-- 数据start -->
      <el-table :data="randomsList" v-loading="isLoading">
        <el-table-column label="编号" width="220">
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column label="题型" width="50">
          <template slot-scope="scope">
            <span>{{scope.row.questionType | questionType}}</span>
          </template>
        </el-table-column>
        <el-table-column label="题目编号" width="220">
          <template slot-scope="scope">
            <p v-for="(value,ind) in scope.row.questionIDs" :key="ind" class="theP" @click="getPreview(value.id)">{{value.number}}</p>
          </template>
        </el-table-column>
        <el-table-column label="录入时间(s)" width="150">
          <template slot-scope="scope">
            <span>{{scope.row.addTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="答题时间(s)">
          <template slot-scope="scope">
            <span>{{scope.row.totalSeconds}}</span>
          </template>
        </el-table-column>
        <el-table-column label="正确率(%)">
          <template slot-scope="scope">
            <span>{{scope.row.accuracyRate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="录入人">
          <template slot-scope="scope">
            <span>{{scope.row.userName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle plain @click.native.prevent="confirmDel(scope, randomsList)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据end -->
      <!-- 分页 -->
      <div class="page">
        <PageTool :paginationPage="paramsData.page" :paginationPagesize="paramsData.pagesize" :total="alertNum" @pageChange="changePage" @pageSizeChange="changePageSize" :isDisabled="isLoading">
        </PageTool>
      </div>
      <!-- end -->
    </el-card>
    <!-- 根据题目编号预览 -->
    <QuestionsPreview :questionID="previewData.id" :show="previewData.it"></QuestionsPreview>
  </div>
</template>
<script>
import { randoms, removeRandoms } from '@/api/hmmm/questions' // 引入接口 组题列表 组题列表删除
import PageTool from '../components/page-tool.vue' // 分页小工具
import QuestionsPreview from '../components/questions-preview.vue' // 预览组件

export default {
  name: 'randoms',
  data () {
    var checkSearchStr = (rule, value, callback) => { // input搜索框表单验证
      const reg = /^[a-z0-9]{1,21}$/
      if (value === '') {
        callback()
      } else if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('无效的关键字'))
      }
    }
    return {
      isLoading: false, // 加载中?
      timer: null, // 设置 节流定时器
      alertNum: 0, // 共几条数据
      alertText: '未查询到数据', // 文字
      randomsList: [], // 列表
      form: {
        keyWordsStr: '' || null // input搜索框中的关键字
      },
      paramsData: { // 组题列表请求参数
        page: 1,
        pagesize: 20,
        keyword: null
      },
      previewData: {
        id: '', // 题目编号id
        it: false // 点击题目编号, 负责变化的变量
      },
      rules: {
        keyWordsStr: [
          { validator: checkSearchStr, trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    PageTool, QuestionsPreview
  },
  mounted () {
    this.getRandoms()
  },
  methods: {
    changePage (num) { // 切换页码
      this.paramsData.page = num

      this.getRandoms()
    },
    changePageSize (num) { // 切换每页几条数据
      this.paramsData.pagesize = num
      this.paramsData.page = 1
      this.getRandoms()
    },
    async getRandoms () { // 获取列表
      this.isLoading = true
      await randoms(this.paramsData).then(res => {
        this.alertNum = res.data.counts
        this.alertText = '查询到' + res.data.counts + '条数据'
        this.randomsList = res.data.items
        this.isLoading = false
      }).catch(err => {
        console.log(err)
        this.$message.error('获取列表失败, 请刷新重试')
        this.isLoading = false
      })
    },
    searchRandoms () { // 根据关键字搜索试题
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.searchTimer()
        } else {
          this.$message.error('关键字格式不正确!!')
        }
      })
    },
    searchTimer () { // 设置节流阀,控制连续点击发送请求
      if (this.timer) return
      this.timer = setTimeout(() => {
        this.paramsData.keyword = this.form.keyWordsStr
        this.paramsData.page = 1
        this.getRandoms()
        this.timer = null
      }, 500)
    },
    async doDel (id) { // 做删除
      await removeRandoms({
        id: id
      }).then(res => {
        if (this.paramsData.page > 1) { // 数据总页数两页及以上时
          // 如果最后一页只有一项数据, 删除这条数据后, 页面应跳转至前一页
          // ↓判断 删除后的数据总页数 是否小于 删除前的数据总页数
          if (Math.ceil((this.alertNum - 1) / this.paramsData.pagesize) < this.paramsData.page) {
            this.paramsData.page = this.paramsData.page - 1
            this.getRandoms() // 页面跳转至前一页
          }
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(err => {
        console.log(err)
        this.$message.error('删除失败, 请刷新重试')
      })
    },
    confirmDel (scope, rows) { // 确认是否删除
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(scope.row.id) // 删后台数据
      }).then(() => {
        this.getRandoms() // 重新获取列表
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    getPreview (id) { // 点击题目编号预览试题
      this.previewData.id = id // 传数据
      this.previewData.it = !this.previewData.it // 取反, 为了让组件监听到变化
    }
  },
  filters: {
    questionType: function (type) {
      if (type === '1') {
        return '单选'
      } else if (type === '2') {
        return '多选'
      } else {
        return '简答'
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  //分页
  .page {
    height: 40px;
    padding: 10px 0px;
    text-align: right;
  }
  //input框
  .ipt {
    width: 200px;
  }

  //清除搜索按钮
  .btn {
    margin-bottom: 0px;
    padding: 0px;
    float: right;
  }

  //题目编号
  .theP {
    padding: 0px;
    margin: 3px;
    color: #409EFF;
    cursor: pointer;
  }
</style>
